package com.choosefine.paycenter.notify.mq.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.*;
import com.choosefine.paycenter.common.utils.ByteArrayStringUtils;
import com.choosefine.paycenter.common.utils.SerialNumberUtils;
import com.choosefine.paycenter.pay.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Comments：监听支付操作状态的消息监听器(支付是否成功的状态这个消息转发给业务系统)
 * Author：Jay Chang
 * Create Date：2017/5/3
 * Modified By：
 * Modified Date：
 * Why & What is modified：
 * Version：v1.0
 */
@Slf4j
@Component("notifyPayMessageListener")
public class NotifyPayMessageListener implements MessageListener {

    @Autowired
    @Qualifier("notifyPayMessageProducer")
    //通知业务系统支付状态消息生产者
    private Producer producer;

    @Value("${aliyun.ons.topic.topicNotify}")
    private String topicNotify;

    @Autowired
    private SerialNumberUtils serialNumberUtils;

    @Autowired
    private PaymentService paymentService;

    public Action consume(Message message, ConsumeContext consumeContext) {
        //这里的msgKey即paySn
        final String msgKey = message.getKey();
        if(serialNumberUtils.isPaySn(msgKey)) {
            final String tag = message.getTag();
            byte[] msgBody = message.getBody();
            String jsonStr = ByteArrayStringUtils.getInstance().byteArray2String(msgBody, "UTF-8");
            JSONObject payOrderMessage = JSON.parseObject(jsonStr);
            //只有非自身支付业务的时候，需要通知业务系统（所以这里需要注意，针对自身（支付系统）发起的各类交易【目前如账单发起付款，转账】bizzSys都应该为SELF）
            if(!"SELF".equalsIgnoreCase(payOrderMessage.getString("bizzSys"))){
                Long finishedAt = paymentService.findFinishedAtByPaySn(msgKey);
                payOrderMessage.put("finishedAt",finishedAt);
                byte[] body = ByteArrayStringUtils.getInstance().string2ByteArray(payOrderMessage.toJSONString(),"UTF-8");
                String newTag = payOrderMessage.getString("bizzSys") + "_" + tag;
                Message messageNotify = new Message(topicNotify,newTag,msgKey,body);
                producer.send(messageNotify);
                return Action.CommitMessage;
            }
        }
        return Action.CommitMessage;
    }
}
